package com.chcit.mobile.mvp.inventory.fragment.Stock;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.chcit.mobile.mvp.inventory.adapter.PackageHistoryAdapter;
import com.chcit.mobile.mvp.inventory.entity.PackageHistoryBean;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.chcit.mobile.mvp.inventory.di.component.DaggerPackageInfoQueryComponent;
import com.chcit.mobile.mvp.inventory.contract.PackageInfoQueryContract;
import com.chcit.mobile.mvp.inventory.presenter.PackageInfoQueryPresenter;
import static com.jess.arms.utils.Preconditions.checkNotNull;
import com.chcit.mobile.R;
import com.xuexiang.xui.widget.edittext.ValidatorEditText;
import com.xuexiang.xui.widget.tabbar.TabControlView;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import java.util.ArrayList;
import java.util.List;


import butterknife.BindView;

public class PackageInfoQueryFragment extends ScanFragment<PackageInfoQueryPresenter> implements PackageInfoQueryContract.View {

    private static final int REQUEST_CODE_SCAN = 788;
    @BindView(R.id.tcv_package_base_select)
    TabControlView tlTabs;
    @BindView(R.id.ve_package_base_no)
    ValidatorEditText etPackageNo;
    @BindView(R.id.include_package_base_info)
    View i1;
    @BindView(R.id.include_package_history_info)
    View i2;
    @BindView(R.id.tv_package_base_productName)
    ValidatorEditText tvProductName;
    @BindView(R.id.tv_package_base_productSpec)
    ValidatorEditText tvProductSpec;
    @BindView(R.id.tv_package_base_manufacturer)
    ValidatorEditText tvManufacturer;
    @BindView(R.id.tv_package_base_qty)
    ValidatorEditText tvQty;
//    @BindView(R.id.tv_package_base_uom)
//    TextView tvUom;
    @BindView(R.id.tv_package_base_lot)
    ValidatorEditText tvLot;
    @BindView(R.id.tv_package_base_guarenteeDate)
    ValidatorEditText tvGuaranteeDate;
    @BindView(R.id.tv_package_base_status)
    ValidatorEditText tvPackageStatusName;
    @BindView(R.id.tv_package_base_productCode)
    ValidatorEditText tvProductCode;
    @BindView(R.id.tv_package_base_locator)
    ValidatorEditText tvLocator;
    @BindView(R.id.rv_history_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.img_package_base_scan)
    AppCompatImageView imgScan;
    ZxingConfig config = null;
    private PackageBean packageBean;
    private List<PackageHistoryBean> packageHistoryBeans = new ArrayList<>();
    private PackageHistoryAdapter packageHistoryAdapter;

    public static PackageInfoQueryFragment newInstance() {
        PackageInfoQueryFragment fragment = new PackageInfoQueryFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerPackageInfoQueryComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_package_info_query, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        //显示引用布局
        i1.setVisibility(View.VISIBLE);
        i2.setVisibility(View.GONE);
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initEvent();
    }

    private void initEvent() {
        //tab的监听事件
        tlTabs.setOnTabSelectionChangedListener((title, value) -> {
            switch (value){
                case "基本信息":
                    //显示引用布局
                    i1.setVisibility(View.VISIBLE);
                    i2.setVisibility(View.GONE);
                    break;
                case "历史信息":
                    //显示引用布局
                    i1.setVisibility(View.GONE);
                    i2.setVisibility(View.VISIBLE);
                    break;
            }

        });

        imgScan.setOnClickListener(v->{
            Intent intent = new Intent(mContext, CaptureActivity.class);
            /*ZxingConfig是配置类
             *可以设置是否显示底部布局，闪光灯，相册，
             * 是否播放提示音  震动
             * 设置扫描框颜色等
             * 也可以不传这个参数
             * */
            if(config==null){
                config= new ZxingConfig();
                config.setPlayBeep(true);//是否播放扫描声音 默认为true
                config.setShake(true);//是否震动  默认为true
                config.setDecodeBarCode(true);//是否扫描条形码 默认为true
                config.setReactColor(R.color.colorAccent);//设置扫描框四个角的颜色 默认为白色
                config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
                config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色
                config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
            }
            intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
            startActivityForResult(intent, REQUEST_CODE_SCAN);
        });

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        etPackageNo.setText(barcodeData);
        queryByPackageNo();
    }

    private void queryByPackageNo() {
        //如果包装号为空，则不进行查询操作
        if (etPackageNo.getText().toString().isEmpty()) {
            return;
        }
        //每次查询，都显示tab1（基本信息）页
        tlTabs.setSelection("基本信息");
        //查询包装信息
        JSONObject params = new JSONObject();
        params.put("packageNo", etPackageNo.getText().toString());
        params.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
        assert mPresenter != null;
        mPresenter.getPakcageBaseInfo(params, list -> {
            packageBean = list.get(0);
            showData();
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                onBarcodeEventSuccess(content);
            }
        }
    }
    private void showData() {
        if (packageBean != null) {
            tvProductName.setText(packageBean.getProductName());
            tvProductSpec.setText(packageBean.getProductSpec());
            tvManufacturer.setText(packageBean.getManufacturer());
            tvQty.setText(packageBean.getQty().toString()+packageBean.getUomName());
            tvProductCode.setText(packageBean.getProductCode());
            tvLocator.setText(packageBean.getLocatorName());
            tvLot.setText(packageBean.getLot());
            tvGuaranteeDate.setText(packageBean.getGuaranteeDate());
            tvPackageStatusName.setText(packageBean.getPackageStatusName());

            //查询包装历史信息
            JSONObject params = new JSONObject();
            params.put("packageNo", etPackageNo.getText().toString());
            assert mPresenter != null;
            mPresenter.getPakcageHistoryInfo(params, list -> {
                packageHistoryBeans = list;
                packageHistoryAdapter = new PackageHistoryAdapter(packageHistoryBeans);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                mRecyclerView.setAdapter(packageHistoryAdapter);
            });
        }

    }
}
